package mgo

import (
	"fmt"
	"gamesdk/common/log"

	mgo "gopkg.in/mgo.v2"
)

var (
	g_session *mgo.Session = nil
	g_user    string
	g_pwd     string
	g_ip      string
)

//连接mango
func Connect(user, pwd, ip string) {
	url := fmt.Sprintf("mongodb://%s", ip)
	if user != "" && pwd != "" {
		url = fmt.Sprintf("mongodb://%s:%s@%s", user, pwd, ip)
	}

	log.Info(url)
	session, err := mgo.Dial(url)
	if err != nil {
		panic(err)
	}
	g_session = session
	g_user = user
	g_pwd = pwd
	g_ip = ip
	log.Info("connect mango success")
}

//获取mango句柄
func GetSingle() *mgo.Session {
	//log.Debug("GetSingle")
	if g_session != nil {
		err := g_session.Ping()
		if err != nil {
			log.Error(err.Error())
			Connect(g_user, g_pwd, g_ip)
		}
		//else {
		// 	log.Debug("ping ok")
		// }
	} else {
		panic("please connect mango")
	}
	return g_session

}

//关掉mango
func Close() {
	if g_session != nil {
		g_session.Close()
		g_session = nil
	}
}
